<template>
	<div>
		<StepTabs :tabs="tabsList" v-model="activeIndex"></StepTabs>
		<div class="from-content" v-if="activeIndex == 1">
			<AplidForm ref="formRef" v-bind="formProjectConfig(subsidyType)" v-model="formModel" @submit="onSubmit">
				<template v-slot:subsidyApplyConfigIdForm>
					<remoteSelect
						class="w-100"
						:disabled="!formModel.subsidyType"
						:key="formModel.subsidyType"
						:paramsObj="{ subsidyType: formModel.subsidyType, isAuthFilter: false, organizationId: userInfo.organizationId }"
						api="view_ofsSubsidyProject_page"
						filterKey="subsidyApplyConfigId"
						filterLabel="projectName"
						propName="projectName"
						placeholder="请选择"
						v-model:modelName="formModel.subsidyProjectName"
						v-model="formModel.subsidyApplyConfigId"
						@change="handleGetProjectInfo"
					></remoteSelect>
				</template>
			</AplidForm>
			<div class="footer-btn fc">
				<el-button @click="formRef.onSubmit()" type="primary">下一步</el-button>
			</div>
		</div>

		<template v-if="activeIndex == 2">
			<div class="config-content">
				<policyArchive :list="nowData.policyRel"></policyArchive>
			</div>
			<div class="footer-btn">
				<div class="block">
					<span class="label">申请日期</span>
					<el-date-picker
						v-model="formModel.belongDate"
						type="month"
						value-format="YYYY-MM-DD"
						:disabled-date="disabledDate"
						placeholder="请选择日期"
					/>
				</div>
				<div class="w-100 fc">
					<el-button @click="handleProd">上一步</el-button>
					<el-button type="primary" @click="handleNext">下一步</el-button>
				</div>
			</div>
		</template>

		<template v-if="activeIndex == 3">
			<ApplyReport :nowRowData="{ ...nowData, ...formModel }" @refresh-change="onRefreshChange"></ApplyReport>
			<div class="footer-btn">
				<div class="w-100 fc">
					<el-button @click="handleProd">上一步</el-button>
					<el-button type="primary" @click="handleSubmitApply">提交申请</el-button>
				</div>
			</div>
		</template>
	</div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import apiMod from '@/apiMod/index'
import remoteSelect from '@/components/AplidCrud/src/AplidRemote/index'
import StepTabs from '@/views/instOperate/components/StepTabs/index.vue'
import policyArchive from '@/views/instOperate/components/policyArchive/index.vue'
import ApplyReport from './ApplyReport/index.vue'
import { formProjectConfig } from '../config'
import { getStore } from '@/utils/store'
import { md5 } from '@/utils/encdecrpt'
import bus from '@/utils/eventbus'

let listData = null
bus.on('postListData', (data) => {
	listData = data
})

const props = withDefaults(
	defineProps<{
		subsidyType?: string | number
		bedApplyType?: string | number
	}>(),
	{}
)
const emit = defineEmits(['refresh'])
const formModel: any = ref({
	belongDate: '',
	subsidyType: props.subsidyType,
})

const userInfo = getStore('userInfo') || {}
const orgInfo = getStore('organizationInfo') || {}
const formRef = ref(null)
const activeIndex = ref(1)

let projectDate = ref({
	projectStartDate: '',
	projectEndDate: '',
})

const disabledDate = (date) => {
	let startDate = new Date(projectDate.value.projectStartDate)
	let endDate = new Date(projectDate.value.projectEndDate)
	let month = date.getMonth() + 1
	return (month != 4 && month != 10) || date.getTime() > new Date() || date.getTime() < startDate || date.getTime() > endDate
}

const tabsList = [
	{ label: '01.选择补贴项目', value: 1, tip: '选择对应的补贴项目' },
	{ label: '02.申请须知', value: 2, tip: '关于养老从业人员岗位津贴的政策文件' },
	{ label: '03.提交材料', value: 3, tip: '根据政策文件，提供相关文件' },
]

const nowData: any = ref({})

const handleNext = () => {
	if (!formModel.value.belongDate) {
		ElMessage.warning('请选择申请日期')
		return
	}
	nowData.value.belongDate = formModel.value.belongDate

	const getYearMonth = (belongDate) => {
		const year = belongDate.replace('年', '-').replace('月', '').split('-')[0]
		const month = belongDate.replace('年', '-').replace('月', '').split('-')[1]
		return { year, month }
	}
	apiMod
		.view_subsidy_getData({
			projectId: formModel.value.subsidyProjectId,
			creditCode: userInfo.organizationId,
			staffIdCard: formModel.value.applicateObject,
			...getYearMonth(formModel.value.belongDate),
			applyType: 4, //从业人员岗位传4
		})
		.then((res) => {
			if (res.data == 0) {
				onNext()
			} else if (res.data == 1) {
				ElMessage.warning('该员工本月已提交补贴申请，不可重复提交!')
			} else if (res.data == 2) {
				ElMessage.warning('已申请相同类型补贴，请勿重复申请!')
			} else if (res.data == 3) {
				ElMessage.warning('该员工在该月已申请岗位补贴，不可再次申请入职补贴!')
			} else if (res.data == 4) {
				ElMessage.warning('该员工本月已申请补贴，不可再申请!')
			}
		})
}

const onNext = () => {
	if (activeIndex.value < tabsList.length) {
		activeIndex.value += 1
	}
}

const handleGetProjectInfo = (data) => {
	if (data && data.id) {
		projectDate.value.projectStartDate = data.projectStartDate
		projectDate.value.projectEndDate = data.projectEndDate
		formModel.value.subsidyProjectId = data.id
	}
}
const handleProd = () => {
	if (activeIndex.value > 1 && activeIndex.value <= tabsList.length) {
		activeIndex.value -= 1
	}
}
const onSubmit = (form, done) => {
	// 获取项目配置
	apiMod.view_ofsSubsidyApplyConfig_view(form.subsidyApplyConfigId).then((res) => {
		nowData.value = {
			...(res.data || {}),
		}
		onNext()
	})

	done()
}

const onRefreshChange = (formId) => {
	formModel.value.applyNo = formId
}

const handleSubmitApply = async () => {
	if (!listData || !listData.qualificationCertificateNameAndGrade) {
		ElMessage.error('该人员没有相关证书，不可提交')
	} else {
		const params: any = {
			belongDate: formModel.value.belongDate,
			creditCode: userInfo.organizationId,
			applicateObject: formModel.value.applicateObject,
			subsidyProjectId: formModel.value.subsidyProjectId,
			applyNo: formModel.value.applyNo,
			staffIdCard: formModel.value.applicateObject,
			applyType: 4, // 从业人员岗位传4
		}
		if (!formModel.value.applyNo) {
			const str = [
				params?.creditCode,
				params?.belongDate?.replace('-', '').substring(0, 6),
				params?.subsidyProjectId,
				params.staffIdCard || undefined,
			]
				.filter(Boolean)
				.join('_')
			params.applyNo = md5(str)
		}
		if (props.subsidyType == 1) {
			params.applyType = 5
			params.bedApplyType = props.bedApplyType || 1
		}

		apiMod.view_ofsSubsidyApply_add(params).then(() => {
			ElMessage.success('提交成功')
			if (props.subsidyType == 1) {
				// 新增勘察记录 床位补贴类型
				apiMod
					.view_ofsSubsidyApplySurvey_add({
						orgName: orgInfo.organizationName,
						creditCode: orgInfo.creditCode,
						orgAddress: orgInfo.organizationAddress,
						applyNo: params.applyNo,
						burdenUserName: orgInfo.burdenUserName,
						burdenUserPhone: orgInfo.burdenUserPhone,
					})
					.then(() => {
						emit('refresh')
					})
					.catch(() => {
						emit('refresh')
					})
			} else {
				emit('refresh')
			}
		})
	}
}

watch(
	() => formModel.value.subsidyType,
	() => {
		formModel.value.subsidyProjectName = undefined
		formModel.value.subsidyApplyConfigId = undefined
	},
	{
		immediate: true,
	}
)
</script>

<style scoped lang="scss">
.from-content {
	width: 50%;
	margin: 100px auto;
}
.config-content {
	padding: 12px;
	margin-top: 20px;
	border: 1px solid #dcdcdc;
	border-radius: 10px;
}
.footer-btn {
	margin-top: 32px;
	.block {
		display: flex;
		align-items: center;
		.label {
			margin-right: 12px;
		}
	}
}
</style>
